package org.example.order.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.application.context.RequestContext;
import org.example.order.controller.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class RequestContextAspect {
    private static final Logger logger = LoggerFactory.getLogger(RequestContextAspect.class);

    @Pointcut("execution(* org.example.order.controller.*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object executeWithRequestContext(ProceedingJoinPoint joinPoint) throws Throwable {
        try (RequestContext requestContext = new RequestContext()) {
            requestContext.setTenantId(getTenantByToken());
            try {
                return joinPoint.proceed(joinPoint.getArgs());
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                return Result.fail(ex.getMessage());
            }
        }
    }

    private String getTenantByToken() {
        // mock context
        return "tenant-mock";
    }
}
